package com.day10.study.swing_demo;

import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

public class TreeFrame extends JFrame {
    private static final int WINDOW_WIDTH = 640;
    private static final int WINDOW_HEIGHT = 640;

    private JTree tree;

    public TreeFrame() {
        initComponent();
        addComponent();
        addListener();
        initWindows();
    }

    private void initComponent() {
        DefaultMutableTreeNode top = new DefaultMutableTreeNode("Qst");
        DefaultMutableTreeNode dept1 = new DefaultMutableTreeNode("财务");
        DefaultMutableTreeNode dept2 = new DefaultMutableTreeNode("生产");
        DefaultMutableTreeNode dept3 = new DefaultMutableTreeNode("研发");
        DefaultMutableTreeNode emp1 = new DefaultMutableTreeNode("张三");
        DefaultMutableTreeNode emp2 = new DefaultMutableTreeNode("李四");
        top.add(dept1);
        dept1.add(emp1);
        dept1.add(emp2);
        top.add(dept2);
        top.add(dept3);
        tree = new JTree(top);
    }

    private void addComponent() {
        this.add(tree);
    }

    private void addListener() {
        tree.addTreeSelectionListener(
                new TreeSelectionListener() {
                    @Override
                    public void valueChanged(TreeSelectionEvent e) {
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                        String tmp = (String) node.getUserObject();
                        System.out.println(tmp);
                    }
                }
        );
    }

    private void initWindows() {
        this.setTitle("TreeFrame");
        this.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        new TreeFrame();
    }
}
